<template>
  <div class="back-top">
    <transition name="fade">
      <div v-show="show" @click.stop="click" class="go-back" :style="style">
        <slot>
          <Icon type="ios-arrow-up" size="28" color="#fff" />
        </slot>
      </div>
    </transition>
  </div>
</template>
<script>
import { scrollToTop } from "@libs/utils";
export default {
  name: "BackTop",
  props: {
    right: {
      //元素距离右边的距离
      type: Number,
      default: 10
    },
    bottom: {
      //元素距底部距离
      type: Number,
      default: 10
    },
    target: {
      //触发滚动的对象
      type: String
    },
    visibilityHeight: {
      //滚动高度达到此值才显示
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      element: document.body, //默认body节点
      show: false
    };
  },
  computed: {
    style() {
      return {
        right: `${this.right}px`,
        bottom: `${this.bottom}px`
      };
    }
  },
  methods: {
    scroll(e) {
      this.show = e.target.scrollTop > this.visibilityHeight;
    },
    click() {
      scrollToTop(0, this.element);
      this.$emit("on-click");
    },
    init() {
      //初始化DOM节点，并且监听scroll事件
      if (this.target) {
        this.element = document.querySelector(this.target);
        if (!this.element) {
          throw new Error(`未找到${this.target}节点`);
        }
      }
      this.element.setAttribute("style", "scroll-behavior: smooth");
      this.element.addEventListener("scroll", this.scroll);
    }
  },
  watch: {
    target() {
      //target变化，销毁之前监听的事件，并且重新初始化
      this.element.removeEventListener("scroll", this.scroll);
      this.init();
    }
  },

  mounted() {
    this.init();
  },
  destroyed() {
    //组件销毁，销毁掉监听的事件
    this.element.removeEventListener("scroll", this.scroll);
  }
};
</script>
<style lang="stylus" scoped>
@import './index.styl'
</style>